import { createSlice, PayloadAction } from '@reduxjs/toolkit';

interface Tab {
    title: string;
    path: string;
}

interface TabsState {
    tabs: Tab[];
    activeTab: string;
}

const initialState: TabsState = {
    tabs: [{ title: '首页', path: '/home' }],
    activeTab: '/home',
};

const tabsSlice = createSlice({
    name: 'tabs',
    initialState,
    reducers: {
        addTab: (state, action: PayloadAction<Tab>) => {
            const exists = state.tabs.some((tab) => tab.path === action.payload.path);
            if (!exists) {
                state.tabs.push(action.payload);
            }
            state.activeTab = action.payload.path;
        },
        removeTab: (state, action: PayloadAction<string>) => {
            // 不允许删除首页
            if (action.payload === '/home') return;

            const index = state.tabs.findIndex((tab) => tab.path === action.payload);
            if (index !== -1) {
                state.tabs.splice(index, 1);

                // 如果删除的是当前激活的标签，则激活前一个或下一个标签
                if (state.activeTab === action.payload) {
                    state.activeTab = state.tabs[index]
                        ? state.tabs[index].path
                        : state.tabs[index - 1].path;
                }
            }
        },
        setActiveTab: (state, action: PayloadAction<string>) => {
            state.activeTab = action.payload;
        },
    },
});

export const { addTab, removeTab, setActiveTab } = tabsSlice.actions;
export default tabsSlice.reducer;